package com.hjj.springboot.controller;


//微信用户Controller

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hjj.springboot.constant.SystemConstant;
import com.hjj.springboot.entity.R;
import com.hjj.springboot.entity.WxUserInfo;
import com.hjj.springboot.mapper.WxUserInfoMapper;
import com.hjj.springboot.properties.WeixinProperties;
import com.hjj.springboot.service.IWxUserInfoService;
import com.hjj.springboot.util.DateUtil;
import com.hjj.springboot.util.HttpClientUtil;
import com.hjj.springboot.util.JwtUtils;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private WeixinProperties weixinProperties;

    @Autowired
    private HttpClientUtil httpClientUtil;

    @Autowired
    private IWxUserInfoService wxUserInfoService;

    @Value("${avatarUrlImagesFilePath}")
    private String avatarUrlImagesFilePath;

    //    微信用户登录
    @RequestMapping("/wxlogin")
    public R wxLogin(@RequestBody WxUserInfo wxUserInfo) {
        System.out.println(wxUserInfo.getCode());
        // 通过jscode2session 获取openId
        String jscode2sessionUrl=weixinProperties.getJscode2sessionUrl()+"?appid="+weixinProperties.getAppid()+"&secret="+weixinProperties.getSecret()+"&js_code="+wxUserInfo.getCode()+"&grant_type=authorization_code";
        String result=httpClientUtil.sendHttpGet(jscode2sessionUrl);
        JSONObject jsonObject= JSON.parseObject(result);
        String openid=jsonObject.get("openid").toString();
        System.out.println(openid);
        //  插入用户到数据库 判断用户是否存在 不存在的话 插入 存在的话 更新
        WxUserInfo resultWxUserInfo = wxUserInfoService.getOne(new QueryWrapper<WxUserInfo>().eq("openid", openid));
        if(resultWxUserInfo==null){ // 不存在 插入用户
            System.out.println("不存在 插入用户");
            wxUserInfo.setOpenid(openid);
            wxUserInfo.setRegisterDate(new Date());
            wxUserInfo.setLastLoginDate(new Date());
            wxUserInfo.setTelNumber(wxUserInfo.getTelNumber());
            wxUserInfoService.save(wxUserInfo);
        }else{  // 存在 更新用户信息
            System.out.println("存在 更新用户信息");
            resultWxUserInfo.setTelNumber(wxUserInfo.getTelNumber());
            resultWxUserInfo.setLastLoginDate(new Date());
            wxUserInfoService.updateById(resultWxUserInfo);
        }

        // 利用jwt生成token返回到前端
        String token = JwtUtils.createJWT(openid, wxUserInfo.getNickName(), SystemConstant.JWT_TTL);
        WxUserInfo wxUserInfo1=wxUserInfoService.getOne(new QueryWrapper<WxUserInfo>().eq("openid", openid));
        Map<String,Object> resultMap=new HashMap<>();
        resultMap.put("token",token);
        resultMap.put("openid",openid);
        resultMap.put("userInfo",wxUserInfo1);
        return R.ok(resultMap);

    }

//    上传头像
@RequestMapping("/uploadImage")
public Map<String,Object> uploadImage(@RequestParam("avatarUrl") MultipartFile file) throws Exception {
    Map<String,Object> reultMap=new HashMap<>();
    if(!file.isEmpty()){
        String originalFilename= file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String newFileName= DateUtil.getCurrentDateStr()+suffix;
        FileUtils.copyInputStreamToFile(file.getInputStream(),new File(avatarUrlImagesFilePath+newFileName));
        reultMap.put("code",0);
        reultMap.put("msg","上传成功");
        Map<String,Object> dataMap=new HashMap<>();
        dataMap.put("title",newFileName);
        dataMap.put("src","img/avatarUrl/"+newFileName);
        reultMap.put("data",dataMap);
    }
    return reultMap;
}

    @PostMapping("/wxupdate")
    public R wxUpdate(@RequestBody WxUserInfo wxUserInfo) {
        System.out.println(wxUserInfo);
        wxUserInfo.setNickName(wxUserInfo.getNickName());
        wxUserInfo.setAvatarUrl(wxUserInfo.getAvatarUrl());
        wxUserInfoService.update(wxUserInfo,new QueryWrapper<WxUserInfo>().eq("openid", wxUserInfo.getOpenid()));
        return R.ok();
    }
    
}
